package arch.dao.impl.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import arch.dao.user.UserRoleDao;
import arch.domain.user.Role;
import arch.domain.user.User;
import arch.domain.user.relation.UserRole;
/**
 * 
 * @author ZhaoWangLong Sep 7, 2012
 *
 */
@Repository("userRoleDao")
public class UserRoleImpl implements UserRoleDao {
	@Resource private JdbcTemplate jdbcTemplate;
	
	public Integer query(String sql, Object... objects) {
		return this.jdbcTemplate.queryForInt(sql,objects);
	}

	@SuppressWarnings("unchecked")
	public List<UserRole> queryList(String sql, Object... objects) {
		return this.jdbcTemplate.query(sql, objects, new RowMapper(){
			public Object mapRow(ResultSet rs, int i) throws SQLException {
				UserRole userRole = new UserRole();
				
				Role role = new Role();
				role.setRoleId(rs.getString("ROLE_ID"));
				userRole.setRole(role);
				
				User user = new User();
				user.setUserId(rs.getString("USER_ID"));
				userRole.setUser(user);
				
				userRole.setIndex(rs.getInt("INDEX"));
				return userRole;
			}
			
		});
	}

	public void remove(UserRole userRole) {
		String sql = "delete from ID_ROLE_USER where (ROLE_ID, USER_ID) = (?,?) ";
		
		this.jdbcTemplate.update(sql,new Object[]{
			userRole.getRole().getRoleId(),
			userRole.getUser().getUserId()
		});
	}

	public void merge(UserRole entity) {
		String sql = "update ID_ROLE_USER set INDEX = ? where (ROLE_ID, USER_ID) = (?,?) ";

		this.jdbcTemplate.update(sql,new Object[]{
				entity.getIndex(),
				entity.getRole().getRoleId(),
				entity.getUser().getUserId()
		});
	}

	public void persist(UserRole entity) {
		String sql = "insert into ID_ROLE_USER (ROLE_ID, USER_ID, INDEX) values (?,?,?)";
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getRole().getRoleId(),
				entity.getUser().getUserId(),
				entity.getIndex()
		});
	}

	public void persist(List<UserRole> userRoles) {
		String sql = "insert into ID_ROLE_USER (ROLE_ID, USER_ID, INDEX) values (?,?,?)";
		this.jdbcTemplate.batchUpdate(sql, new UserRoleBatchInsertSetter(userRoles));
	}

	public void remove(List<UserRole> userRoles) {
		String sql = "delete from ID_ROLE_USER where (ROLE_ID, USER_ID) = (?,?) ";
		this.jdbcTemplate.batchUpdate(sql, new UserRoleBatchDeleteSetter(userRoles));
	}

	public void remove(String sql, Object... objects) {
		this.jdbcTemplate.update(sql,objects);
	}
}
